# encoding=utf8

from app.extensions import db


class Machine(db.Model):
    __tablename__ = 'machine'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    code = db.Column(db.String(50), nullable=False, unique=True)
    name = db.Column(db.String(50))
    ip = db.Column(db.String(500))
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))

    def __repr__(self):
        return self.username

    @staticmethod
    def is_exist(code):
        machine = Machine.query.filter_by(code=code).first()
        return machine is not None, machine

    @staticmethod
    def add(machine):
        try:
            db.session.add(machine)
            db.session.commit()
            return True
        except Exception as e:
            db.session.rollback()
        return False

    @staticmethod
    def update(code, ip):
        machine = Machine.query.filter_by(code=code).first()
        if machine is None:
            return
        machine.ip = ip
        db.session.commit()